package com.smart.framework.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * <p><b>Description:</b>  TODO
 * <p><b>Company:</b>
 *
 * @author created by Jesse Xu at 14:41 on 2019/10/8
 * @version V0.1
 * @classNmae DatabaseHelper
 */
public class DatabaseHelper {

    private static ThreadLocal<Connection> CONNECTION_HOLDER= new ThreadLocal<Connection>(){
        @Override
        public void set(Connection value) {
            super.set(value);
        }

        @Override
        public void remove() {

            super.remove();
            Connection conn =get();
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    LOGGER.error(" connection close failure");
                    throw new RuntimeException(e);
                }
            }
        }
    };

    private final static Logger LOGGER = LoggerFactory.getLogger(DatabaseHelper.class);
    static void beginTransaction() {
        Connection conn = getConnection();
        if (conn != null) {
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                LOGGER.error("begin transaction failure");
                throw new RuntimeException(e);
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }
    static void commitTransaction() {
        Connection conn = getConnection();
        if (conn != null) {
            try {
                conn.commit();
                conn.close();
            } catch (SQLException e) {
                LOGGER.error("commit transaction failure");
                throw new RuntimeException(e);
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }

    static void rollbackTransaction() {
        Connection conn = getConnection();
        if (conn != null) {
            try {
                conn.rollback();
                conn.close();
            } catch (SQLException e) {
                LOGGER.error("rollback transaction failure");
                throw new RuntimeException(e);
            }finally {
                CONNECTION_HOLDER.remove();
            }
        }
    }
    private static Connection getConnection() {
        Connection  conn=null;

        try {
              Class.forName("");
              conn=DriverManager.getConnection("");
        } catch (ClassNotFoundException|SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
